/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.server.modules.sys.web.material;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.server.common.persistence.Page;
import com.server.modules.gen.util.GenUtils;
import com.server.modules.sys.entity.Dict;
import com.server.modules.sys.entity.material.MaterialUpload;
import com.server.modules.sys.service.DictService;
import com.server.modules.sys.service.material.MaterialUploadService;
import com.server.modules.sys.vo.web.MaterialUploadWrap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.server.common.config.Global;
import com.server.common.web.BaseController;
import com.server.common.utils.StringUtils;
import com.server.modules.sys.entity.material.MaterialType;
import com.server.modules.sys.service.material.MaterialTypeService;

/**
 * 资料属性类别表Controller
 * @author 王磊
 * @version 2016-09-12
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/material/materialType")
public class MaterialTypeController extends BaseController {

	@Autowired
	private MaterialTypeService materialTypeService;

	@Autowired
	private MaterialUploadService materialUploadService;

    @Autowired
    private DictService dictservice;
	
	@ModelAttribute
	public MaterialType get(@RequestParam(required=false) String id) {
		MaterialType entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = materialTypeService.get(id);
		}
		if (entity == null){
			entity = new MaterialType();
		}
		return entity;
	}
	
	@RequiresPermissions("sys:material:materialType:view")
	@RequestMapping(value = {"list", ""})
	public String list(MaterialType materialType, HttpServletRequest request, HttpServletResponse response, Model model) {
		List<MaterialType> list = materialTypeService.findList(materialType); 
		model.addAttribute("list", list);
		return "modules/sys/material/materialTypeList";
	}

	@RequiresPermissions("sys:material:materialType:view")
	@RequestMapping(value = "form")
	public String form(MaterialType materialType, Model model) {
		if (materialType.getParent()!=null && StringUtils.isNotBlank(materialType.getParent().getId())){
			materialType.setParent(materialTypeService.get(materialType.getParent().getId()));
			// 获取排序号，最末节点排序号+30
			if (StringUtils.isBlank(materialType.getId())){
				MaterialType materialTypeChild = new MaterialType();
				materialTypeChild.setParent(new MaterialType(materialType.getParent().getId()));
				List<MaterialType> list = materialTypeService.findList(materialType); 
				if (list.size() > 0){
					materialType.setSort(list.get(list.size()-1).getSort());
					if (materialType.getSort() != null){
						materialType.setSort(materialType.getSort() + 30);
					}
				}
			}
		}
		if (materialType.getSort() == null){
			materialType.setSort(30);
		}
		model.addAttribute("materialType", materialType);
		model.addAttribute("config", GenUtils.getConfig());
		return "modules/sys/material/materialTypeForm";
	}

	@RequiresPermissions("sys:material:materialType:edit")
	@RequestMapping(value = "save")
	public String save(MaterialType materialType, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, materialType)){
			return form(materialType, model);
		}
		materialTypeService.save(materialType);
		addMessage(redirectAttributes, "保存资料属性成功");
		return "redirect:"+Global.getAdminPath()+"/sys/material/materialType/?repage";
	}
	
	@RequiresPermissions("sys:material:materialType:edit")
	@RequestMapping(value = "delete")
	public String delete(MaterialType materialType, RedirectAttributes redirectAttributes) {
		materialTypeService.delete(materialType);
		addMessage(redirectAttributes, "删除资料属性成功");
		return "redirect:"+Global.getAdminPath()+"/sys/material/materialType/?repage";
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<MaterialType> list = materialTypeService.findList(new MaterialType());
		for (int i=0; i<list.size(); i++){
			MaterialType e = list.get(i);
			if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}

	@RequiresPermissions("sys:material:materialType:view")
	@RequestMapping(value = {"memberMaterialList"})
	public String memberMaterialList(MaterialType materialType, String memberId, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(StringUtils.isNotBlank(memberId)){
			materialType.setParent(new MaterialType("0"));
			Page<MaterialType> page = new Page<>(request, response);
			page.setPageSize(10);
			materialType.setPage(page);
            Page<MaterialType> page1 = materialTypeService.findPage(page, materialType);
            model.addAttribute("page", page1);
		}
		return "modules/sys/member/load/materialList";
	}

    @RequiresPermissions("sys:material:materialType:view")
    @RequestMapping(value = {"memberMaterialUploadList"})
    public String memberMaterialUploadList(String view, String memberId, HttpServletRequest request, HttpServletResponse response, Model model) {
        if(StringUtils.isNotBlank(memberId)/*&&StringUtils.isNotBlank(materialTypeId)*/){
            MaterialUpload query=new MaterialUpload();
        //    query.setTypeId(materialTypeId);
            query.setMemberId(memberId);

            List<MaterialUpload> list = materialUploadService.findList(query);
			Map<String,List<MaterialUpload>> mapTemp=new HashMap<>();
			//给上传资料分组
			for (MaterialUpload materialUpload : list) {
				if(!mapTemp.containsKey(materialUpload.getGroupId())&&!"1".equals(materialUpload.getTypeId())){
					List<MaterialUpload> listTemp =new ArrayList<>();
					listTemp.add(materialUpload);
					mapTemp.put(materialUpload.getGroupId(),listTemp);
				}else if(!"1".equals(materialUpload.getTypeId())){
					mapTemp.get(materialUpload.getGroupId()).add(materialUpload);
				}
			}
			//根据已上传的客户资料反查资料类型
            Map<MaterialType,List<MaterialUpload>> ret=new LinkedHashMap<>();
			for (List<MaterialUpload> materialUploads : mapTemp.values()) {
                String typeId = materialUploads.get(0).getTypeId();
                //获取资料类型
                MaterialType materialType = materialTypeService.get(typeId);
                MaterialType materialTypeParent= materialTypeService.get(materialType.getParentId());
                MaterialType qeury=new MaterialType();
                qeury.setParent(materialTypeParent);
                List<MaterialType> children = materialTypeService.findList(qeury);
                //类型为radiobox或select要去字典表查询对应的值
                for (MaterialType child : children) {
                    if(("radiobox".equals(child.getType())||"select".equals(child.getType()))&&StringUtils.isNotBlank(child.getKeyName())){
                        String keyName = child.getKeyName();
                        Dict dict=new Dict();
                        dict.setType(keyName);
                        child.setKeyValues( dictservice.findList(dict));
                    }
                }
                materialTypeParent.setChildren(children);
                ret.put(materialTypeParent,materialUploads);
            }
            //查询所有资料类型
            MaterialType query2=new MaterialType();
            query2.setParent(new MaterialType("0"));
            List<MaterialType> list1 = materialTypeService.findList(query2);
            for (MaterialType materialType : list1) {
                MaterialType qeury=new MaterialType();
                qeury.setParent(materialType);
                List<MaterialType> children = materialTypeService.findList(qeury);
                //类型为radiobox或select要去字典表查询对应的值
                for (MaterialType child : children) {
                    if(("radiobox".equals(child.getType())||"select".equals(child.getType()))&&StringUtils.isNotBlank(child.getKeyName())){
                        String keyName = child.getKeyName();
                        Dict dict=new Dict();
                        dict.setType(keyName);
                        child.setKeyValues( dictservice.findList(dict));
                    }
                }
                materialType.setChildren(children);
            }
            model.addAttribute("typeList",list1);
            model.addAttribute("ret",ret);
        }
		if(StringUtils.isNotBlank(view)){
			model.addAttribute("view",view);
			return "modules/sys/member/load/materialUploadList-apply";
		}else{
			return "modules/sys/member/load/materialUploadList";
		}

    }
    @ResponseBody
    @RequestMapping(value = "saveMemberMaterialUpload")
    public Object saveMemberMaterialUpload(@RequestParam(required=true) String memberId, String groupId,
         MaterialUploadWrap wrap, String isNew) throws Exception {
    	
        return materialUploadService.insertMemberMuByGroup(wrap,memberId,groupId,isNew);
    }
    @ResponseBody
    @RequestMapping(value = "delMemberMaterialUpload")
    public Object delMemberMaterialUpload(@RequestParam(required=true) String memberId, @RequestParam(required=true) String groupId,HttpServletResponse response) throws Exception {
        return materialUploadService.delMemberMaterialUpload(memberId,groupId);
    }



	
}